package com.rjpacket.chileme.app.fragments;


import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.rjpacket.chileme.app.Constants;
import com.rjpacket.chileme.app.R;
import com.rjpacket.chileme.app.WebActivity;
import com.rjpacket.chileme.app.adapters.CanteenListAdapter;
import com.rjpacket.chileme.app.adapters.ViewPagerCommonAdapter;
import com.rjpacket.chileme.app.models.MainHeadDown;
import com.rjpacket.chileme.app.models.MainHeadUp;
import com.rjpacket.chileme.app.models.MainHeadView;
import com.rjpacket.chileme.app.models.Restaurant;
import com.rjpacket.chileme.app.tasks.*;
import com.rjpacket.chileme.app.tasks.Process;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

public class MainFragment extends Fragment implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, Process, View.OnClickListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2, ListTaskInterface {

    private int headerViewsCount;

    private PullToRefreshListView refresh;

    private ViewPagerCommonAdapter adapter;

    private ViewPager viewPager;

    private RadioGroup rg;

    private List<MainHeadUp> list;
    private CanteenListAdapter adapter1;
    private List<Restaurant> data;

    public MainFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View ret = null;

        ret = inflater.inflate(R.layout.fragment_main, container, false);

        //获得刷新控件
        refresh = (PullToRefreshListView) ret.findViewById(R.id.restaurant_pull_to_refresh_list_view);
        //设置两边都能刷新
        refresh.setMode(PullToRefreshBase.Mode.BOTH);

        //绑定监听器
        refresh.setOnRefreshListener(this);
        Resources res = getResources();
        Drawable drawable = res.getDrawable(R.drawable.spinner_20_outer_holo);

        // 设置加载图标
        refresh.setLoadingDrawable(drawable);
        // 设置加载中的标题
        refresh.setRefreshingLabel("下拉可以刷新");
        // 设置“松开”提醒
        refresh.setReleaseLabel("松开即可刷新");

        //获得ListView
        ListView listView = refresh.getRefreshableView();
        //设置分割线
        listView.setDividerHeight(2);

        Resources resources = getActivity().getResources();


        // resources.getDrawable()

        listView.setDivider(new ColorDrawable(0x00ffff));

        headerViewsCount = listView.getHeaderViewsCount();

        if (listView != null) {

            data = new LinkedList<Restaurant>();
            //绑定适配器
            adapter1 = new CanteenListAdapter(data, getActivity());
            listView.setAdapter(adapter1);
            String url = Constants.CANTEEN_LIST_URL;
            checkNetWork();
            StoreListTask task = new StoreListTask(this);
            task.execute(url);
            //listView.setAdapter();
            //listView绑定点击事件, 点击进入餐厅详情
            listView.setOnItemClickListener(this);
        }


        //添加HeadView
        View headView = inflater.inflate(R.layout.main_headview, listView, false);

        listView.addHeaderView(headView);

        //做主界面联动效果
        viewPager = (ViewPager) headView.findViewById(R.id.main_viewpager);

        rg = (RadioGroup) headView.findViewById(R.id.main_rg);

        //TODO headView点击事件测试，难点与ListView点击事件冲突
        View youhui = headView.findViewById(R.id.enter_youhui);
        View fujin = headView.findViewById(R.id.enter_fujin);
        View waimai = headView.findViewById(R.id.enter_waimai);
        youhui.setOnClickListener(this);
        fujin.setOnClickListener(this);
        waimai.setOnClickListener(this);

        list = new LinkedList<MainHeadUp>();

        adapter = new ViewPagerCommonAdapter(getActivity(), list);

        adapter.setEnterViewPager(this);

        viewPager.setAdapter(adapter);

        viewPager.setOnPageChangeListener(this);

        rg.setOnCheckedChangeListener(this);
        // Inflate the layout for this fragment
        return ret;
    }


    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    /**
     * ViewPager滑动，实现联动
     *
     * @param i
     */
    @Override
    public void onPageSelected(int i) {

        View view = rg.getChildAt(i);

        if (view != null && view instanceof RadioButton) {

            RadioButton rb = (RadioButton) view;

            rb.setChecked(true);
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    /**
     * 点击事件，实现联动
     *
     * @param radioGroup
     * @param i
     */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {

        int count = radioGroup.getChildCount();

        int position = -1;

        for (int j = 0; j < count; j++) {

            View view = radioGroup.getChildAt(j);

            if (view != null && view instanceof RadioButton) {

                RadioButton rb = (RadioButton) view;

                if (rb.isChecked()) {

                    position = j;

                    break;
                }
            }
        }
        if (position > -1) {

            viewPager.setCurrentItem(position, true);
        }
    }

    /**
     * 接收异步的回调接口
     *
     * @param result
     */
    @Override
    public void processResult(JSONObject result) {
        if (result != null) {

            MainHeadView headView = new MainHeadView();

            headView.parseJSON(result);

            list = headView.getUp();

            adapter.notifyDataSetChanged();
        }
    }

    /**
     * HeadView的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {

        Object tag = view.getTag();
        if (tag != null) {
            if (tag instanceof Integer) {
                int pos = (Integer) tag;
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("url", list.get(pos).getUrl());
                startActivity(intent);
            }
        } else {

            switch (view.getId()) {

                case R.id.enter_youhui:

                case R.id.enter_waimai:

                    break;

                case R.id.enter_fujin:

                    break;
            }
        }
    }

    /**
     * 餐厅的选项点击事件
     *
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }

    /**
     * 数据刷新
     *
     * @param refreshView
     */
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

    }


    /**
     * 检测网络状态
     */
    private void checkNetWork() {

        ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info != null) {
            boolean b = info.isAvailable();
            if (!b) {
                Toast.makeText(getActivity(), "您的网络不可用，请检查网络后再试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void processListResult(JSONObject jsonObject) {
        if (jsonObject != null) {
            Restaurant res = new Restaurant();
            res.parseJSON(jsonObject);

            data.addAll(0, res.getData());
            adapter1.notifyDataSetChanged();
        }
    }

}